package top.canyue.word_range.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import top.canyue.word_range.annotation.ValidatePhoneNumber;
import top.canyue.word_range.exception.PhoneNumberException;
import top.canyue.word_range.pojo.dto.UserDto;
import top.canyue.word_range.pojo.po.User;

import java.util.regex.Pattern;

@Aspect
@Component
public class PhoneNumberValidationAspect {
    private static final Pattern PHONE_NUMBER_PATTERN = Pattern.compile("^1[3-9]\\d{9}$");

    private boolean validatePhoneNumber(String phoneNumber) {
        if (!StringUtils.hasText(phoneNumber) || !PHONE_NUMBER_PATTERN.matcher(phoneNumber).matches()){
            throw new PhoneNumberException();
        }
        return true;
    }


    @Around("@annotation(validatePhoneNumber)")
    public Object around(ProceedingJoinPoint joinPoint, ValidatePhoneNumber validatePhoneNumber) throws Throwable {
        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
            if (arg instanceof User) {
                User user = (User) arg;
                String phone = user.getPhone();
                validatePhoneNumber(phone);
            }
            if (arg instanceof UserDto) {
                UserDto userdto = (UserDto) arg;
                String phone = userdto.getPhone();
                validatePhoneNumber(phone);
            }
        }
        return joinPoint.proceed();
    }


}
